<template>
  <el-container>
    <el-header height="30px">
      <el-row type="flex">
        <el-col :span="6">
          <el-input v-model="searchUser" placeholder="输入用户名" style="width: 70%" clearable @clear="getUserList"></el-input>
          <el-button type="primary" @click="getUserList">搜索</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="success" @click="dialogVisible = true">添加用户</el-button>
          <el-dialog
              title="添加"
              :visible.sync="dialogVisible"
              :append-to-body="true"
              width="30%">
            <el-form :model="userAddForm" label-width="auto" size="small">
              <el-form-item label="用户名：">
                <el-input v-model="userAddForm.userName"></el-input>
              </el-form-item>
              <el-form-item label="昵称：">
                <el-input v-model="userAddForm.nikeName"></el-input>
              </el-form-item>
              <el-form-item label="密码：">
                <el-input v-model="userAddForm.password"></el-input>
              </el-form-item>
              <el-form-item label="头像url：">
                <el-input v-model="userAddForm.headUrl"></el-input>
              </el-form-item>
              <el-form-item label="角色：">
                <el-select v-model="userAddForm.roles" placeholder="请选择角色" multiple filterable>
                  <el-option
                      v-for="item in roleList"
                      :key="item.id"
                      :label="item.roleName"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="addUser" :loading="addUserButtonLoading">添加</el-button>
                <el-button type="info" @click="dialogVisible = false">取消</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-table :data="userList">
        <el-table-column label="用户名" width="180" prop="userName" />
        <el-table-column label="昵称" width="180" prop="nikeName" />
        <el-table-column label="头像url" width="180" prop="headUrl">
          <template slot-scope="scope">
            <el-image :src="scope.row.headUrl" fit="cover" style="width: 80px"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="180" prop="enabled" :formatter="enabledFilter"/>
        <el-table-column label="创建时间" width="180" prop="createTime" :formatter="timeFilter"/>
        <el-table-column label="修改时间" width="180" prop="updateTime" :formatter="timeFilter"/>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="toUpdateUser(scope.row)">修改</el-button>
            <el-button type="text" size="mini" @click="deleteUserById(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
          title="修改"
          :visible.sync="updateUserDialogVisible"
          :append-to-body="true"
          width="30%">
        <el-form :model="updateUserForm" label-width="auto" size="small">
          <el-form-item label="用户名：">
            <el-input v-model="updateUserForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="昵称：">
            <el-input v-model="updateUserForm.nikeName"></el-input>
          </el-form-item>
          <el-form-item label="头像url：">
            <el-input v-model="updateUserForm.headUrl"></el-input>
          </el-form-item>
          <el-form-item label="角色：">
            <el-select v-model="userRoleList" placeholder="请选择角色" multiple filterable>
              <el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateUser" :loading="addUserButtonLoading">修改</el-button>
            <el-button type="info" @click="updateUserDialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-main>
    <el-footer>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="sizePage"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </el-footer>

  </el-container>
</template>

<script>
import {list, addUser, checkUsername, pageUser, getRoleByUserId, updateUserAndUserRole, deleteUserById} from "@/api/User";
import {formateDate} from "@/util/TimeFormat";
import { roleAllList } from "@/api/Role";

export default {
  name: "UserTab",
  data(){
    return{
      userList: [],
      currentPage: 1,
      sizePage: 10,
      total: 0,
      dialogVisible: false,
      userAddForm: {},
      updateUserForm: {},
      roleList: [],
      userRoleList: [],
      addUserButtonLoading: false,
      updateUserDialogVisible: false,
      inputVisible: false,
      inputValue: '',
      searchUser: '',
    }
  },

  created() {
    this.init()
  },

  methods: {

    init(){
      this.getUserList()
      this.getRoleList()
    },

    handleSizeChange(val){
      this.getUserList()
    },

    handleCurrentChange(val){
      this.getUserList()
    },

    handleClose(val){
      console.log(val)
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.updateUserRoleTagInput.$refs.input.focus();
      });
    },

    addUserRole(val) {
      console.log(val)
      console.log(this.updateUserForm.id)
    },

    toUpdateUser(user){
      getRoleByUserId(user.id).then(res => {
        this.userRoleList = []
        this.updateUserDialogVisible = true
        this.updateUserForm = user
        let list1 = res.data.data.list;
        for (let i = 0; i < list1.length; i++) {
          this.userRoleList[i] = list1[i].id
        }
      })
    },

    updateUser(){
      this.addUserButtonLoading = true
      this.updateUserForm.roles = this.userRoleList
      var updateUserForm = this.updateUserForm;
      console.log(updateUserForm)
      updateUserAndUserRole(updateUserForm).then(res => {
        this.$notify.success(res.data.message)
        this.getUserList()
      }).catch(error => {
        this.$notify.error('未知错误')
      }).finally(() => {
        this.addUserButtonLoading = false
        this.updateUserDialogVisible = false
      })
    },

    addUser(){
      this.addUserButtonLoading = true
      let userAddForm = this.userAddForm;
      console.log(userAddForm)
      addUser(userAddForm).then(res => {
        let data = res.data;
        if (data.code === 20000){
          this.$notify.success(data.message)
          this.dialogVisible = false
          this.userAddForm = {}
          this.getUserList()
        }else {
          this.$notify.error(data.message)
        }
      }).finally(() => {
        this.addUserButtonLoading = false
      })
    },

    deleteUserById(user){
      this.$confirm('确定删除吗？', '删除', {
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      }).then(() => {
        deleteUserById(user.id).then(res => {
          if (res.data.code === 20000){
            this.$notify.success(res.data.message)
            this.getUserList()
          }else {
            this.$notify.error(res.data.message)
          }
        })
      }).catch(() => {
        this.$message.info('取消删除')
      })

    },

    getUserList() {
      let currentPage = this.currentPage;
      let sizePage = this.sizePage;
      let searchUser = this.searchUser;
      pageUser(currentPage, sizePage, this.searchUser).then(res => {
        this.userList = res.data.data.list
        this.total = res.data.data.total
      }).catch()
    },

    getRoleList() {
      roleAllList().then(res => {
        this.roleList = res.data.data.list
      })
    },

    enabledFilter(row, column, cellValue, index){
      if (cellValue === 1){
        return '正常'
      }else {
        return '封禁'
      }
    },

    timeFilter(row, column, cellValue, index){
      var date = new Date(cellValue * 1000);
      return formateDate(date, "yyyy年MM月dd日")
    },
  }
}
</script>

<style scoped>

</style>